package com.heima.comment.service.impl;

import java.math.BigDecimal;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.ApUserFeign;
import com.heima.model.common.dtos.CommentRepayDTO;
import com.heima.model.common.dtos.CommentRepayLikeDTO;
import com.heima.model.common.dtos.CommentRepaySaveDTO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.ApComment;
import com.heima.model.common.pojos.ApCommentRepay;
import com.heima.model.common.pojos.ApCommentRepayLike;
import com.heima.model.common.vo.ApCommentRepayVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private ApUserFeign apUserFeign;

    //加载评论回复列表
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //判断参数
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //设置查询条件
        Query commentRepayQuery = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        //设置排序条件
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        commentRepayQuery.with(sort);
        //设置分页条件
        PageRequest pageable = PageRequest.of(0, dto.getSize());
        commentRepayQuery.with(pageable);
        //查询
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(commentRepayQuery, ApCommentRepay.class);
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            //未登录,直接返回评论回复列表
            return ResponseResult.okResult(apCommentRepays);
        }
        //登录了,根据当前列表的回复id集合和用户id查询回复点赞列表
        //获取当前评论回复信息的id集合
        List<String> commentRepayIds = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        Query commentRepayLikeQuery = Query.query(Criteria.where("_id").in(commentRepayIds).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(commentRepayLikeQuery, ApCommentRepayLike.class);
        //非空判断
        if (apCommentRepayLikes.size() == 0) {
            //当前用户在当前列表中给任何评论点赞,直接返回列表
            return ResponseResult.okResult(apCommentRepays);
        }
        //当前用户在当前的评论回复中点过赞,创建新的集合保存筛选后的评论回复信息
        ArrayList<ApCommentRepay> apCommentRepayList = new ArrayList<>();
        ApCommentRepayVO apCommentRepayVO = null;
        // 筛选出点过赞的评论
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            boolean flag = true;
            for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                if (apCommentRepay.getCommentId().equals(apCommentRepayLike.getCommentRepayId())) {
                    apCommentRepayVO = new ApCommentRepayVO();
                    BeanUtils.copyProperties(apCommentRepayLike, apCommentRepayVO);
                    apCommentRepayVO.setOperation((short) 0);
                    flag = false;
                }
            }
            if (flag) {
                apCommentRepayList.add(apCommentRepay);
            } else {
                apCommentRepayList.add(apCommentRepayVO);
            }
        }
        return ResponseResult.okResult(apCommentRepayList);
    }

    //保存评论回复
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //获取登录用户id
        Integer userId = AppThreadLocalUtils.getUser().getId();
        //非空判断
        if (userId == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        String newContent = null;
        try {
            //使用阿里云内容审核
            newContent = scanContent(dto.getContent());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //调用远程服务,查询当前登录用户信息
        ResponseResult<ApUser> userResp = apUserFeign.findUserById(userId);
        //非空判断
        if (userResp.getCode() != 0 || userResp.getData() == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "当前用户不存在!");
        }
        //获取用户信息
        ApUser user = userResp.getData();
        //根据评论id查询评论,判断是否存在
        Query commentRepayQuery = Query.query(Criteria.where("_id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(commentRepayQuery, ApComment.class);
        //非空判断
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前回复的评论不存在!");
        }
        //保存评论回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(userId);
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(newContent);
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        //修改评论参数
        Update update = new Update();
        update.set("reply", apComment.getReply() + 1).set("updatedTime", new Date());
        mongoTemplate.updateMulti(commentRepayQuery, update, ApComment.class);
        //响应调用者
        return ResponseResult.okResult();
    }

    //保存评论回复的点赞信息
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //获取当前登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        //非空判断
        if (user == null) {
            //未登录
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //已经登录,验证回复信息是否存在,根据回复id查询
        Query commentRepayQuery = Query.query(Criteria.where("_id").is(dto.getCommentRepayId()));
        ApCommentRepay commentRepay = mongoTemplate.findOne(commentRepayQuery, ApCommentRepay.class);
        if (commentRepay == null) {
            //评论的回复信息不存在
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前评论不存在!");
        }
        //判断操作类型
        if (dto.getOperation() == (short) 0) {
            //点赞,查询是否已经点过赞
            Query apCommentRepayLikeQuery = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(apCommentRepayLikeQuery, ApCommentRepayLike.class);
            if (apCommentRepayLike != null) {
                //已经点过赞
                //创建集合,保存最新点赞数量
                HashMap<String, Integer> likesMap = new HashMap<>();
                likesMap.put("likes", commentRepay.getLikes());
                //响应调用者
                ResponseResult<Object> resp = new ResponseResult<>();
                resp.setData(likesMap);
                resp.setErrorMessage("您已经点过赞,不能再次点赞哦!");
                return resp;
            } else {
                //没有点赞,创建评论回复的点赞对象
                apCommentRepayLike = new ApCommentRepayLike();
                apCommentRepayLike.setAuthorId(user.getId());
                apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
                apCommentRepayLike.setOperation((short) 0);
                //保存到数据库
                mongoTemplate.save(apCommentRepayLike);
                //评论回复的对象,点赞数量+1
                Update update = new Update();
                update.set("likes", commentRepay.getLikes() + 1);
                mongoTemplate.updateMulti(commentRepayQuery, update, ApCommentRepay.class);
                //创建集合,保存最新点赞数量
                HashMap<String, Integer> likesMap = new HashMap<>();
                likesMap.put("likes", commentRepay.getLikes() + 1);
                //响应调用者
                return ResponseResult.okResult(likesMap);
            }
        } else {
            //取消点赞,查询是否已经点赞
            Query apCommentRepayLikeQuery = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(apCommentRepayLikeQuery, ApCommentRepayLike.class);
            if (apCommentRepayLike == null) {
                //还没有点赞
                //创建集合,保存最新点赞数量
                HashMap<String, Integer> likesMap = new HashMap<>();
                likesMap.put("likes", commentRepay.getLikes());
                ResponseResult<Object> resp = new ResponseResult<>();
                resp.setData(likesMap);
                resp.setErrorMessage("您还没有点赞,不能删除哦!");
                return resp;
            } else {
                //点过赞,删除
                mongoTemplate.remove(apCommentRepayLike);
                //修改评论回复信息-1
                Update update = new Update();
                update.set("likes", commentRepay.getLikes() - 1);
                mongoTemplate.updateMulti(commentRepayQuery, update, ApCommentRepay.class);
                //创建集合,保存最新点赞数量
                HashMap<String, Integer> likesMap = new HashMap<>();
                likesMap.put("likes", commentRepay.getLikes() - 1);
                //响应调用者
                return ResponseResult.okResult(likesMap);
            }
        }
    }

    //内容审核方法
    private String scanContent(String content) throws Exception {
        //校验评论内容是否违规
        Map map = greenTextScan.greenTextScan(content);
        //判断
        String suggestion = (String) map.get("suggestion");
        if (suggestion.equals("block")) {
            //文本中有违规内容,修改
            String filteredContent = (String) map.get("filteredContent");
            return filteredContent;
        }
        if (suggestion.equals("review")) {
            //文本中有不确定内容,转为人工审核
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论中有不确定内容,转人工审核!");
        }
        return content;
    }
}